from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad


def encrypt(data):  # data 为 string
    data = data.encode('utf-8')  # string to byte
    key = get_random_bytes(16)  # 随机生成key用以生成密钥
    encryptor = AES.new(key, AES.MODE_ECB)
    e_data = encryptor.encrypt(pad(data, 16))
    data_key = str([e_data, key])  # list 转 string
    return data_key.encode()  # string 转 byte


def decrypt(data_key):
    data_key = data_key.decode()  # byte 转 string
    data_key = eval(data_key)  # string 转 list
    e_data = data_key[0]
    key = data_key[1]
    decrypter = AES.new(key, AES.MODE_ECB)
    d_data = decrypter.decrypt(e_data)
    d_data = unpad(d_data, 16).decode()  # byte 转 string
    return d_data
